package com.major.crowd.mvc.config;

import com.major.crowd.entity.Admin;
import com.major.crowd.entity.Auth;
import com.major.crowd.entity.Role;
import com.major.crowd.service.api.AdminService;
import com.major.crowd.service.api.AuthService;
import com.major.crowd.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;


@Component
public class CrowdUserDetailsService implements UserDetailsService {

    @Autowired
    private AuthService authService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据账号名称查询Admin对象
        Admin admin = adminService.getAdminByLoginAcct(username);
        //获取AdminId
        Integer adminId = admin.getId();
        //根据Id查询角色
        List<Role> assignedRoles = roleService.getAssignedRole(adminId);
        //根据Id查询权限
        List<String> authNames = authService.getAssignedAuthNameByAdminId(adminId);

        //创建集合对象存储
        List<GrantedAuthority> authorities = new ArrayList<>();
        //遍历角色 存入集合
        for (Role role :assignedRoles) {
            String roleName = "ROLE_"+role.getName();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleName);
            authorities.add(authority);
        }
        //遍历权限 存入集合
        for (String authName : authNames) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(authName);
            authorities.add(authority);
        }

        //封装SecurityAdmin对象
        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);
        return securityAdmin;
    }
}

